import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: 'main'
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: 'main'
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/page/main/main.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/page/login/login.vue')
  },
  {
    path: '/changeUserinfo',
    name: 'changeUserinfo',
    component: () => import('@/page/change-user-info/userInfo.vue')
  },
  {
    path: '/addArticle',
    name: 'addArticle',
    component: () => import('@/page/main/src/add-article/index.vue')
  },
  {
    path: '/personalCenter',
    name: 'personalCenter',
    component: () => import("@/page/personal-center/PersonalCenter.vue")
  },
  {
    path: '/friends',
    name: 'friends',
    component: () => import("@/page/friends/friends.vue")
  }
]

const router = createRouter({
  routes,
  history: createWebHistory()
})

router.beforeEach(to => {
  const token = localStorage.getItem('token')
  if (to.path !== '/login') {
    if (!token) {
      return '/login'
    }
  } else {
    if (token) {
      router.replace('/main')
    }
  }
  console.log('路由守卫')
})

export default router
